#include <iostream>
#include <unistd.h>
#include <functional>
#include <pthread.h>
#include<vector>
#include <string>
using namespace std;

using funcs = function<void(void)>;
int thread_num = 5;

class thread_data
{
    friend void *my_method(void *f); // 将该函数设为类的友元->函数可以访问类的私有成员
public:
    thread_data(const pthread_t &tid, const string &name, const uint64_t &time, void (*f)(void))
        : _tid(tid), _name(name), _time(time), _fun(f)
    {
        cout << "构造完成" << endl;
    }

private:
    pthread_t _tid;
    uint64_t _time;
    funcs _fun;
    string _name;
};
void print()
{
    cout << "I am a new thread" << endl;
}

void *my_method(void *f) // 新线程执行的代码
{
    thread_data *fun = static_cast<thread_data *>(f);
    while (1)
    {
        cout << "线程tid = " << fun->_tid << "  新线程名: " << fun->_name << "  线程时间: " << fun->_time << endl;
        fun->_fun();
        sleep(1);
    }
}
vector<pthread_t> v;
int main()
{
    for (int i = 0; i < thread_num; i++)
    {
        // 创建线程

        // string tmp = "threat_";
        // tmp += (i + '0' + 1);

        char tmp[20];
        snprintf(tmp,sizeof(tmp),"%s_%d","thread",i+1);

        pthread_t tid;
        thread_data *obj = new thread_data(tid, tmp, (uint64_t)time(nullptr), print);
        v.push_back(tid);
        pthread_create(&tid, nullptr, my_method, obj); // obj是一个void*类型的，对象也可以传
        sleep(1);
    }

    for(auto it:v)
    {
        cout<<it<<" ";
    }
    cout<<endl;
    // 原线程执行
    while (1)
    {
        // cout<<"I am a init thread"<<endl;
        sleep(1);
    }

    return 0;
}